package com.epam.task.web.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epam.task.web.service.AbstractAction;
import com.epam.task.web.service.AbstractActionsFactory;

@WebServlet("/Controller")
public class Controller extends HttpServlet {

    private static final long serialVersionUID = 1L;
    protected AbstractActionsFactory actionsFactory = new AbstractActionsFactory();

    protected String getActionName(HttpServletRequest request) {
        return request.getParameter("action");
    }

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        AbstractAction action = actionsFactory.create(getActionName(request));
        String url = action.perform(request, response);
        if (url != null) {
            request.getRequestDispatcher(url).forward(request, response);
        }
    }

    public void destroy() {
        super.destroy();
    }

}
